package com.app.util;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.app.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class WechatUtil {

    @Resource
    private RedisService redisService;

    /**
     * 获得移动
     *
     * @param mobileCode 移动代码
     * @return {@link String}
     */
    public String getMobile(String mobileCode) {
        //获取access_token
        String token = redisToken();
        // 使用前端code获取手机号码 参数为json格式
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + token;
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("code", mobileCode);
        String response = HttpUtil.post(url, JSONUtil.toJsonStr(paramMap));
        log.info("获取用户手机号 响应:{}", response);
        cn.hutool.json.JSONObject entries = JSONUtil.parseObj(response);
        String phone = entries.getJSONObject("phone_info").getStr("phoneNumber");
        log.info("获取token,{}", token);
        return phone;
    }

    /**
     * redis获取token
     */
    public String redisToken() {

        if (!redisService.hasKey("patrol_access_token")) {
            String token_url = "https://api.weixin.qq.com/cgi-bin/stable_token";
            Map<String, Object> parameters = new HashMap<>();
            parameters.put("grant_type", "client_credential");
            parameters.put("appid", WXConstant.APPID);
            parameters.put("secret", WXConstant.SECRET);
            parameters.put("force_refresh", false);
            JSONObject token = JSON.parseObject(HttpUtil.post(token_url, JSONUtil.toJsonStr(parameters)));
            redisService.set("patrol_access_token", token.getString("access_token"), 3600L);
            return token.getString("access_token");
        } else {
            return redisService.get("patrol_access_token");
        }
    }
}
